import { site_config } from './xhr_res/site-config.js';
import { input_xpath_0 } from './xhr_res/n0.js';
import { input_xpath_1 } from './xhr_res/n1.js';
import { input_xpath_3 } from './xhr_res/n3.js';

// =========================
// 配置常量
// =========================
const SERVER_URL_table0918 = 'http://10.254.11.44:5656/upload';
const MAX_FILE_SIZE_table0918 = 500 * 1024 * 1024; // 500MB
const SUPPORTED_FILE_TYPES_table0918 = ['jpg', 'jpeg', 'png', 'gif', 'tiff'];
const DEFAULT_TOAST_DURATION_table0918 = 3000; // 3秒

console.log('content loading');

let input_xpath = null
let show_icon_flag = false;

for (const key in site_config) {
    if (site_config.hasOwnProperty(key)) {
        const element = getElementByXPath(site_config[key]['xpath']);
        if (!element) {
            continue;
        }

        //console.log('element:'  +  element.textContent)
        if (element.textContent.trim() === site_config[key]['title']) {
            let fname = site_config[key]['fname'];
            if (fname === 'n0.js') { input_xpath = input_xpath_0; show_icon_flag = true; break }
            if (fname === 'n1.js') { input_xpath = input_xpath_1; show_icon_flag = true; break }
            if (fname === 'n3.js') { input_xpath = input_xpath_3; show_icon_flag = true; break }
        }
    }
}

// 封装XPath工具函数，获取单个元素
function getElementByXPath(xpath, context = document) {
    return document.evaluate(
        xpath,
        context,
        null,
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null
    ).singleNodeValue;
}

//显示按钮
function show_icon(show_icon_flag) {
    if (show_icon_flag) {
        document.getElementById('main_table0918').classList.remove('hidden_table0918');
        document.getElementById('main-icon_table0918').classList.remove('main-icon_table0918_filter');
    }
}

// 处理XHR响应，从变量模板动态导入xpath并写入值
async function xhr_callback(data) {
    try {
        if (Array.isArray(input_xpath)) {
            input_xpath.forEach(item => {
                let element = getElementByXPath(item['xpath']);

                if (element) {
                    if (item['input_type'] === 'select') {
                        // 查找匹配文本的option并设置其值                        
                        const options = element.querySelectorAll('option');

                        for (let option of options) {
                            if (option.textContent.trim() === data[item['input_name']].trim()) {
                                element.value = option.value;
                                break;
                            }
                        }
                    } else {
                        element.value = data[item['input_name']] || '';
                    }
                } else {
                    console.warn(`未找到 XPath 为 ${item['xpath']} 的元素`);
                }
            });
        } else {
            console.error('input_xpath 格式错误');
        }
    } catch (error) {
        console.error('动态导入失败:', error);
    }
}

// 显示提示
function showToast(message, duration = DEFAULT_TOAST_DURATION_table0918) {
    document.getElementById('toast-message_table0918').textContent = message;
    document.getElementById('toast_table0918').classList.remove('hidden_table0918');

    setTimeout(() => {
        document.getElementById('toast_table0918').classList.add('hidden_table0918');
    }, duration);
}

// 验证文件类型
function validateFileType(file) {
    const extension = file.name.split('.').pop().toLowerCase();
    return SUPPORTED_FILE_TYPES_table0918.includes(extension);
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}

// 验证文件大小
function validateFileSize(file) {
    return file.size <= MAX_FILE_SIZE_table0918;
}

// 上传文件
async function uploadFile(file) {
    // 显示上传中状态
    document.getElementById('upload-placeholder_table0918').classList.add('hidden_table0918');
    document.getElementById('uploading_table0918').classList.remove('hidden_table0918');

    // 获取文件总大小并格式化
    const totalSize = file.size;
    const formattedTotalSize = formatFileSize(totalSize);

    try {
        // 模拟上传进度
        let progress = 0;
        const progressInterval = setInterval(() => {
            progress += Math.random() * 20;
            if (progress >= 90) {
                progress = 90;
                clearInterval(progressInterval);
                // 显示OCR动画
                document.getElementById('uploading_table0918').classList.add('hidden_table0918');
                document.getElementById('ocr-animation_table0918').classList.remove('hidden_table0918');
            }

            document.getElementById('progress-bar_table0918').style.width = progress + '%';
            document.getElementById('progress-text_table0918').textContent = Math.round(progress) + '%';

            // 更新文件大小显示
            const loadedSize = (totalSize * progress) / 100;
            const formattedLoadedSize = formatFileSize(loadedSize);
            document.getElementById('file-size-text_table0918').textContent = formattedLoadedSize + ' / ' + formattedTotalSize;
        }, 200);

        // 将文件转换为base64
        const fileData = await fileToBase64(file);

        // 通过自定义事件与content script通信
        const response = await new Promise((resolve, reject) => {
            // 监听上传结果
            const successHandler = (event) => {
                if (event.detail.fileName === file.name) {
                    window.removeEventListener('uploadSuccess', successHandler);
                    window.removeEventListener('uploadError', errorHandler);
                    resolve(event.detail.data);
                }
            };

            const errorHandler = (event) => {
                if (event.detail.fileName === file.name) {
                    window.removeEventListener('uploadSuccess', successHandler);
                    window.removeEventListener('uploadError', errorHandler);
                    reject(new Error(event.detail.error));
                }
            };

            window.addEventListener('uploadSuccess', successHandler);
            window.addEventListener('uploadError', errorHandler);

            // 发送上传请求到content script
            window.dispatchEvent(new CustomEvent('requestUpload', {
                detail: {
                    fileData: fileData,
                    fileName: file.name,
                    fileType: file.type,
                    url: SERVER_URL_table0918,
                    input_xpath: JSON.stringify(input_xpath)
                }
            }));
        });

        // 清除进度条定时器
        clearInterval(progressInterval);

        // 上传完成，设置进度条为100%
        document.getElementById('progress-bar_table0918').style.width = '100%';
        document.getElementById('progress-text_table0918').textContent = '100%';

        showToast(`文件 ${file.name} 识别完成！`);

        console.log('返回原始数据:', response);
        try {
            xhr_callback(response);
        } catch (err) {
            console.log(err);
        }

    } catch (error) {
        console.error('Upload error:', error);
        showToast(`文件 ${file.name} 上传失败: ${error.message}`);
    }

    // 恢复上传前状态
    setTimeout(() => {
        document.getElementById('ocr-animation_table0918').classList.add('hidden_table0918');
        document.getElementById('upload-placeholder_table0918').classList.remove('hidden_table0918');

        //隐藏上传框，显示ai图标
        document.getElementById('container_table_table0918').classList.add('hidden_table0918');
        document.getElementById('ai_ico_table0918').classList.remove('hidden_table0918')

        // 重置进度条和文件大小显示
        document.getElementById('progress-bar_table0918').style.width = '0%';
        document.getElementById('progress-text_table0918').textContent = '0%';
        document.getElementById('file-size-text_table0918').textContent = '0 KB / 0 KB';
    }, 500);
}

// 将文件转换为base64的辅助函数
function fileToBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}

// 处理文件
function handleFiles(files) {
    if (files.length === 0) return;

    const file = files[0];

    // 验证文件类型
    if (!validateFileType(file)) {
        showToast(`文件 ${file.name} 格式不支持，仅支持PNG、JPG、JPEG、GIF、TIFF图片格式`);
        return;
    }

    // 验证文件大小
    if (!validateFileSize(file)) {
        showToast(`文件 ${file.name} 超过大小限制 (500MB)`);
        return;
    }

    // 上传文件
    uploadFile(file);
}


// 图标按钮拖拽功能实现
function makeDraggable(element) {
    let isDragging = false;
    let startX, startY, startLeft, startTop;

    function dragStart(e) {
        // 只在鼠标左键或触摸时开始拖拽
        if (e.type === 'mousedown' && e.button !== 0) return;

        isDragging = true;

        // 获取鼠标/触摸位置
        const clientX = e.type === 'touchstart' ? e.touches[0].clientX : e.clientX;
        const clientY = e.type === 'touchstart' ? e.touches[0].clientY : e.clientY;

        // 记录开始位置
        startX = clientX;
        startY = clientY;

        // 获取元素当前位置
        const rect = element.getBoundingClientRect();
        startLeft = rect.left;
        startTop = rect.top;

        // 设置样式
        element.style.cursor = 'grabbing';
        element.style.userSelect = 'none';

        // 阻止默认行为和事件冒泡
        e.preventDefault();
        e.stopPropagation();
    }

    function drag(e) {
        if (!isDragging) return;

        e.preventDefault();

        // 获取当前鼠标/触摸位置
        const clientX = e.type === 'touchmove' ? e.touches[0].clientX : e.clientX;
        const clientY = e.type === 'touchmove' ? e.touches[0].clientY : e.clientY;

        // 计算移动距离
        const deltaX = clientX - startX;
        const deltaY = clientY - startY;

        // 设置新位置
        const newLeft = startLeft + deltaX;
        const newTop = startTop + deltaY;

        element.style.left = newLeft + 'px';
        element.style.top = newTop + 'px';
        element.style.right = 'auto'; // 移除right定位
    }

    function dragEnd(e) {
        if (!isDragging) return;

        isDragging = false;
        element.style.cursor = 'grab';

        e.preventDefault();
        e.stopPropagation();
    }

    // 添加事件监听器
    element.addEventListener('mousedown', dragStart);
    element.addEventListener('touchstart', dragStart, { passive: false });

    document.addEventListener('mousemove', drag);
    document.addEventListener('touchmove', drag, { passive: false });

    document.addEventListener('mouseup', dragEnd);
    document.addEventListener('touchend', dragEnd);

    // 设置初始样式
    element.style.cursor = 'grab';
    element.style.userSelect = 'none';

    // 为了避免与原有的onclick事件冲突，我们需要特殊处理
    const originalOnclick = element.onclick;
    element.onclick = function (e) {
        // 如果刚刚进行了拖拽，则不执行原有的点击事件
        if (Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5) {
            e.preventDefault();
            e.stopPropagation();
            return false;
        }
        // 否则执行原有的点击事件
        if (originalOnclick) {
            return originalOnclick.call(this, e);
        }
    };
}

// 等待元素存在的函数
function waitForElements() {
    const fileUploadElement = document.getElementById('file-upload_table0918');
    const uploadContainerElement = document.getElementById('upload-container_table_table0918');
    const aiIconElement = document.getElementById('ai_ico_table0918');

    if (fileUploadElement && uploadContainerElement && aiIconElement) {
        // 元素都存在，初始化事件监听器
        initializeEventListeners();
        show_icon(show_icon_flag);
        // 初始化拖拽功能
        makeDraggable(aiIconElement);
        console.log('AI图标拖拽功能已启用');
    } else {
        // 元素还不存在，100ms后重试
        setTimeout(waitForElements, 500);
    }
}

// 初始化事件监听器
function initializeEventListeners() {
    // 文件选择事件
    document.getElementById('file-upload_table0918').addEventListener('change', function () {
        handleFiles(this.files);
        // 重置input，以便可以重复上传同一个文件
        this.value = '';
    });

    // 拖拽上传事件监听
    document.getElementById('upload-container_table_table0918').addEventListener('dragover', function (e) {
        e.preventDefault();
        this.classList.add('drag-over_table0918');
    });

    document.getElementById('upload-container_table_table0918').addEventListener('dragleave', function () {
        this.classList.remove('drag-over_table0918');
    });

    document.getElementById('upload-container_table_table0918').addEventListener('drop', function (e) {
        e.preventDefault();
        this.classList.remove('drag-over_table0918');

        if (e.dataTransfer.files.length) {
            handleFiles(e.dataTransfer.files);
        }
    });
}

// 启动等待元素函数
//不使用(()=>{})()是因为有个setTimeout，可以递归重试
waitForElements();
